package com.shensi.appCollect.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shensi.api.admin.domian.integral.dto.CustomerPointsRecord;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.pojo.CouponIssue;
import com.shensi.appCollect.pojo.CouponTemplate;
import com.shensi.appCollect.constantEnum.integralTypeEnum;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.vo.IntegralOrderVo;
import com.shensi.appCollect.service.*;
import com.shensi.appCollect.utils.*;
import com.shensi.appCollect.utils.redis.RedisCacheUtil;
import com.shensi.appCollect.utils.weixinapp.WxPushUtil;
import com.shensi.appCollect.utils.weixinapp.WxTemplateData;
import com.shensi.appCollect.utils.weixinapp.WxTemplateMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/*
 * <Title> IntegralShoppingMallController </Title>
 * <Description> 油站积分商城模块 </Description>
 * @Date 2021年2月24日
 */
@Controller
//@QuJiaRequest()
@CrossOrigin
@Api(tags = "积分商城")
public class IntegralShoppingMallController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(IntegralShoppingMallController.class);
    @Resource
    private IntegralWaresService integralWaresService;
    @Resource
    private IntegralOrderService integralOrderService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private IntegralShopPicService integralShopPicService;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private PointsMerchandiseWriteOffRecordService pointsMerchandiseWriteOffRecordService;
    @Resource
    private CouponController couponController;
    @Resource
    private CouponService couponService;
    @Value("${qujia.domainName}")
    private String domainName;



    //获取积分商城轮播图片
    @RequestMapping(value = "/getIntegralShopPicInfoList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取积分商城轮播图片", httpMethod = "GET", notes = "积分商城轮播图片")
    public String getIntegralShopPicInfoList(@ApiParam(value = "油站ID", required = true) @RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null){
            IntegralShopPic integralShopPic = new IntegralShopPic();
            integralShopPic.setStationId(stationId);
            IntegralShopPic integralShopPics = integralShopPicService.getIntegralShopPicList(integralShopPic);
            List<String> list = new ArrayList<>();
            if(integralShopPics !=null && integralShopPics.getImage1() !=null){
                list.add(integralShopPics.getImage1());
            }
            if(integralShopPics !=null && integralShopPics.getImage2() !=null){
                list.add(integralShopPics.getImage2());
            }
            if(integralShopPics !=null && integralShopPics.getImage3() !=null){
                list.add(integralShopPics.getImage3());
            }
            if(integralShopPics !=null && integralShopPics.getImage4() !=null){
                list.add(integralShopPics.getImage4());
            }
            if(integralShopPics !=null && integralShopPics.getImage5() !=null){
                list.add(integralShopPics.getImage5());
            }
            Map map = new HashMap();
            map.put("listPic", list);
            resultData=ResultData.success(map);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站积分商品详情信息
    @RequestMapping(value = "/getIntegralWaresInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取油站积分商品详细信息", httpMethod = "GET", notes = "油站积分商品详细信息")
    public String getIntegralWaresInfo(@ApiParam(value = "商品ID", required = true)@RequestParam Integer id){
        logger.info("積分商城商品Id：" + id);
        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //返回结果集
        ResultData resultData = null;
        if(id !=null){
            IntegralWares integralWares = new IntegralWares();
            integralWares.setId(id);
            IntegralWares integralWaresInfo = integralWaresService.getIntegralWaresInfo(integralWares);
            if(null !=integralWaresInfo && "1".equals(integralWaresInfo.getIsCouponProduct())){

                String issueIditems = integralWaresInfo.getCouponIssueIds();
                // 拆分字符串
                String[] parts = issueIditems.split(",");
                ArrayList<String> issueIds = new ArrayList<>();
                for (String part : parts) {
                    String trimmedPart = part.trim();
                    issueIds.add(trimmedPart);
                }
                Map<String, Object> param = new HashMap<>();
                List<CouponTemplate> couponTemplateListNew = new ArrayList<>();
                if(null !=issueIds && issueIds.size()>0){
                    for(String issueId :issueIds ){
                        param.put("couponIssueId", issueId);
                        List<CouponIssue> couponIssues = couponService.selectCouponListByCouponIssueId(param);
                        if (couponIssues.size() == 0){
                            continue;
                        }
                        CouponIssue couponIssue = couponIssues.get(0);
                        List<Station> staList = couponIssue.getStaList();
                        List<String> collect = staList.stream().map(Station::getStationName).collect(Collectors.toList());
                        List<CouponTemplate> couponTemplateList = couponIssue.getCouponTemplateList();

                        if (null != couponTemplateList && couponTemplateList.size() > 0) {
                            String join = StringUtils.join(collect.toArray(), ",");
                            for (CouponTemplate couponTemplate : couponTemplateList) {
                                // 检查当前CouponTemplate的couponTemplateId是否已经存在于couponTemplateListNew中
                                boolean isDuplicate = couponTemplateListNew.stream()
                                        .anyMatch(existingTemplate -> existingTemplate.getCouponTemplateId().equals(couponTemplate.getCouponTemplateId()));

                                // 如果当前CouponTemplate的couponTemplateId不重复，则添加到couponTemplateListNew中
                                if (!isDuplicate) {
                                    couponTemplate.setCouponStaNames(join);
                                    couponTemplateListNew.add(couponTemplate);
                                }
                            }
                        }

                    }
                    param.put("couponIssueId",  issueIds.get(0));
                    List<CouponIssue> couponIssues = couponService.selectCouponListByCouponIssueId(param);
                    couponIssues.get(0).setCouponTemplateList(couponTemplateListNew);
                    integralWaresInfo.setCouponIssue(couponIssues.get(0));
                }
            }

            resultData=ResultData.success(integralWaresInfo);
        }else{
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }
    /**
     * 查询客户积分记录列表
     */
    @GetMapping("/integral/list")
    @ResponseBody
    public String anonylist(  CustomerPointsRecord customerPointsRecord)
    {
        if(customerPointsRecord.getQueryInMonth()!=null){
            customerPointsRecord.setQueryInMonth(customerPointsRecord.getQueryInMonth()+"-01");
        }

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        List<CustomerPointsRecord> recordList = customerPointsRecordService.getCustomerPointsRecordList(customerPointsRecord);
        ResultData   resultData;
        if(recordList.size() == 0){
            resultData = ResultData.error("查无数据");
        }else{
            resultData = ResultData.success(recordList);
        }
        return gson.toJson(resultData);
    }

    //获取油站积分商品信息
    @RequestMapping(value = "/getIntegralWaresInfoList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取油站积分商品列信息", httpMethod = "GET", notes = "油站积分商品列信息")
    public String getIntegralWaresInfoList(@ApiParam(value = "油站ID", required = true) @RequestParam Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        try {
            if(stationId !=null){
                IntegralWares integralWares = new IntegralWares();
                integralWares.setStationId(stationId);
                List<IntegralWares> integralWaresInfoList = integralWaresService.getIntegralWaresInfoList(integralWares);
                resultData=ResultData.success(integralWaresInfoList);
            }else{
                resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }catch (Exception e){
            e.printStackTrace();
            resultData=ResultData.error(CodeMsg.YEWU_FAIL);
            logger.error("获取油站积分商品错误信息："+ e.getMessage());
        }
        return gson.toJson(resultData);
    }

    //生成积分订单
    @RequestMapping(value = "/insertIntegralOrder", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "生成积分订单", httpMethod = "POST", notes = "生成积分订单")
    public String insertIntegralOrder(@RequestBody IntegralOrder request) throws Exception {
        logger.info("/insertIntegralOrder-" + request.getMobilePhone() + "--request:"+ request.toString());
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(request.getMobilePhone()) && null !=request.getStationId() && null != request.getExchangeNum() && null != request.getWaresId()){
            //订单规则 时间+6位随机数
            String integralOrderNo = System.currentTimeMillis()+ RandomStringUtils.randomNumeric(6);
            String gzhAppId ="";
            String gzhAppSecret ="";
            String stationName = "";        //油站名称

            //获取油站信息
            Station station = enterpriseService.selectStationById(request.getStationId());
            stationName = station.getStationName();
            Integer enterpriseId = station.getEnterpriseId();
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            //更新商品已售数量
            List<IntegralWares> integralWaresInfoList = integralWaresService.getIntegralWaresInfoList(IntegralWares.builder().id(request.getWaresId()).build());
            //此处会有线程安全问题，但单一加油站积分兑换实际业务并发性不高，故没做处理；
            if(integralWaresInfoList !=null && integralWaresInfoList.size() ==1 && integralWaresInfoList.get(0).getWaresCount() >0 &&
                    integralWaresInfoList.get(0).getWaresCount() >= request.getExchangeNum()){
                //更新用户积分
                String surplusPoints ="";           //剩余积分
                String orderSumIntegral ="";        //订单消费总积分
                //获取用户信息
                AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().stationId(enterpriseId).mobilePhone(request.getMobilePhone()).build());
                if(appUserInfo !=null){
                    logger.info("/insertIntegralOrder-" + request.getMobilePhone() + "--兑换前的积分:" + appUserInfo.getIntegral());
                    //获取商品信息
                    IntegralWares integralWaresInfo = integralWaresService.getIntegralWaresInfo(IntegralWares.builder().id(request.getWaresId()).build());
                    if(new BigDecimal(integralWaresInfo.getSaleIntegral().intValue()).equals(new BigDecimal(request.getIntegral()))){
                        BigDecimal multiply = new BigDecimal(integralWaresInfo.getSaleIntegral().toString()).multiply(new BigDecimal(request.getExchangeNum())); //该订单总积分
                        orderSumIntegral = multiply.toString();
                        //用户剩余积分且大于订单积分
                        if(new BigDecimal(appUserInfo.getIntegral()).compareTo(new BigDecimal(orderSumIntegral)) == 1 || new BigDecimal(appUserInfo.getIntegral()).compareTo(new BigDecimal(orderSumIntegral)) == 0){
                            BigDecimal points = new BigDecimal(appUserInfo.getIntegral()).subtract(multiply);
                            surplusPoints = points.toString();

//发放数量
                            int     exchangeNum  = request.getExchangeNum();
                            //积分兑换优惠券
                            for (int i = 0; i < exchangeNum; i++) {
                                if (StringUtils.isNotBlank(integralWaresInfo.getIsCouponProduct()) && "1".equals(integralWaresInfo.getIsCouponProduct())) {

                                    String issueIditems = integralWaresInfo.getCouponIssueIds();
                                    // 拆分字符串
                                    String[] parts = issueIditems.split(",");
                                    ArrayList<String> issueIds = new ArrayList<>();
                                    for (String part : parts) {
                                        String trimmedPart = part.trim();
                                        issueIds.add(trimmedPart);
//                                    ResultData resultData1 = couponController.sendCoupon(drawCoupon, issueIds, 6, "0",null,null);
//                                    if (resultData1.getRetCode() != 0){
//                                        return gson.toJson(ResultData.error(CodeMsg.COUPON_NOT_ENOUGHT));
//                                    }
                                    }
                                    if (issueIds.size() > 0) {
                                        try {
                                            couponController.drawCouponsForIntegral(request.getMobilePhone(), issueIds, 6);
                                        } catch (Exception e) {
                                            // 在这里处理异常，可以打印错误信息或执行其他操作
                                            System.out.println(e);
                                        }
                                    }

                                }
                            }
                            //更新用户积分
                            appUserInfoService.updateAppUserIntegral(AppUserInfo.builder()
                                    .mobilePhone(request.getMobilePhone())
                                    .stationId(enterpriseId)
                                    .integral(points.intValue())
                                    .build());
                            //更新商品数量信息
                            integralWaresService.updateIntegralWaresInfo(IntegralWares.builder()
                                    .id(request.getWaresId())
                                    .waresCount(integralWaresInfo.getWaresCount()-request.getExchangeNum())
                                    .waresOutCount(integralWaresInfo.getWaresOutCount()+request.getExchangeNum())
                                    .build());
                            //插入客户积分记录
                            customerPointsRecordService.insertCustomerPointsRecordInfo(CustomerPointsRecord.builder()
                                    .createTime(new Date())
                                    .customerName(appUserInfo.getBlogNickName())
                                    .action(integralTypeEnum.EXCHANGE_GOODS)
                                    .mobilePhone(request.getMobilePhone())
                                    .stationId(request.getStationId())
                                    .recordType("-")
                                    .integral(multiply.intValue())
                                    .orderNo(integralOrderNo)
                                    .build());
                            customerPointsRecordService.sendwxgzh(request.getStationId(),request.getMobilePhone(),multiply.intValue(),points.intValue(),"-");
                            //生成订单
                            boolean couponOrNot = StringUtils.isNotBlank(integralWaresInfo.getIsCouponProduct()) && "1".equals(integralWaresInfo.getIsCouponProduct());
                            boolean b = integralOrderService.insertIntegralOrder(IntegralOrder.builder()
                                    .waresId(request.getWaresId())
                                    .mobilePhone(request.getMobilePhone())
                                    .integralOrderNo(integralOrderNo)
                                    .stationId(request.getStationId())
                                    .exchangeNum(request.getExchangeNum())
                                    .exchangeTime(new Date())
                                    .integral(points.intValue())
                                    .waresName(integralWaresInfo.getWaresName())
                                    .waresPic(integralWaresInfo.getWaresPic())
                                    .waresDetail(integralWaresInfo.getWaresDetail())
                                    .integral(multiply.intValue())
                                    .customerName(appUserInfo.getBlogNickName())
                                    .status("1")
                                    .couponOrNot(couponOrNot  ? 1 : 0)
                                    .build());
                            logger.info("/insertIntegralOrder-" + request.getMobilePhone() + "--此次兑换成功-" + integralWaresInfo.getWaresName() + "--" + "数量为" + request.getExchangeNum());
                            if (b){
                                //积分消息推送
                                if(enterprise !=null  && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())){
                                    gzhAppId = enterprise.getGzhAppId();
                                    gzhAppSecret = enterprise.getGzhAppSecret();
                                    if(StringUtils.isNotBlank(appUserInfo.getBlogOpenid())){
                                        //templateType("2")代表 积分模板
                                        GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder().templateType("2").stationId(enterpriseId).build());
                                        if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                                            //新推送 公众号积分消耗消息推送
                                            WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                                            wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                                            wxTemplateMsg.setTouser(appUserInfo.getBlogOpenid());
                                            Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                                            templateDataMap.put("first",      WxTemplateData.builder().value("您好！您已成功在"+stationName+"完成积分商品兑换：").build());
                                            templateDataMap.put("keyword1",   WxTemplateData.builder().value(appUserInfo.getBlogNickName()).build());
                                            templateDataMap.put("keyword2",   WxTemplateData.builder().value(integralOrderNo).build());
                                            templateDataMap.put("keyword3",   WxTemplateData.builder().value(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).build());
                                            if(StringUtils.isNotBlank(integralWaresInfo.getIsCouponProduct()) && "1".equals(integralWaresInfo.getIsCouponProduct())){
                                                String url = "https://"+domainName+"/"+ enterprise.getEnterpriseId() +"/coupon";
                                                wxTemplateMsg.setUrl(url);
                                                templateDataMap.put("keyword4",   WxTemplateData.builder().value(integralWaresInfo.getWaresName()+"   x "+ request.getExchangeNum() + " (点击查看)").color("#0080FF").build());
                                            }else {
                                                templateDataMap.put("keyword4",   WxTemplateData.builder().value(integralWaresInfo.getWaresName()+"   x "+ request.getExchangeNum()).build());
                                            }
                                            templateDataMap.put("keyword5",   WxTemplateData.builder().value(orderSumIntegral).build());
                                            templateDataMap.put("remark",     WxTemplateData.builder().value("截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+"，您在"+stationName+"的积分值还剩余 "+surplusPoints+" 分").build());
                                            wxTemplateMsg.setData(templateDataMap);
                                            wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
                                        }
                                        //推送消息
                                        //couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                    }else {
                                        logger.info("用户没有公众号openId");
                                    }
                                }
                                resultData=ResultData.success(CodeMsg.SUCCESS);
                            }else {
                                resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
                            }
                        }else {
                            resultData=ResultData.error(CodeMsg.INTEGRAL_INSUFFICIENT);
                        }
                    }else {
                        resultData=ResultData.error(CodeMsg.CHECK_DATA_ERROR);
                    }
                }
            }else {
                resultData=ResultData.error(CodeMsg.WARSECOUNT_FAIL);
            }

        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "用户手机号，商品Id， 油站ID，兑换数量 有未传参数");
        }
        return gson.toJson(resultData);
    }

    //获取用户积分订单列表
    @RequestMapping(value = "/getUserIntegralOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户积分订单列表", httpMethod = "GET", notes = "用户积分订单列表")
    public String getUserIntegralOrderList(@ApiParam(value = "客户手机号", required = true)@RequestParam String mobilePhone,
                                           @ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(mobilePhone) && enterpriseId !=null){
            IntegralOrder integralOrder = new IntegralOrder();
            integralOrder.setMobilePhone(mobilePhone);
            integralOrder.setStationId(enterpriseId);
            List<IntegralOrderVo> integralOrderList = integralOrderService.getUserIntegralOrderList(integralOrder);
            resultData=ResultData.success(integralOrderList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取客户积分信息
    @RequestMapping(value = "/getCustomerPointsInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取客户积分信息", httpMethod = "GET", notes = "获取客户积分信息")
    public String getCustomerPointsInfo(@ApiParam(value = "客户手机号", required = true)@RequestParam String mobilePhone,
                                        @ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(mobilePhone) && enterpriseId !=null){
            //新修订 用户积分信息已添加到app_user_info
            AppUserInfo appUserInfo = appUserInfoService.getAppUserInfoAndBalance(AppUserInfo.builder().stationId(enterpriseId).mobilePhone(mobilePhone).build());
            resultData=ResultData.success(appUserInfo);
        }else {
            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取客户积分记录信息
    @RequestMapping(value = "/getCustomerPointsRecordList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取客户积分记录信息", httpMethod = "GET", notes = "获取客户积分记录信息")
    public String getCustomerPointsRecordList(@ApiParam(value = "客户手机号", required = true)@RequestParam String mobilePhone,
                                              @ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(mobilePhone) && enterpriseId !=null){
            CustomerPointsRecord customerPointsRecord  =new CustomerPointsRecord();
            customerPointsRecord.setMobilePhone(mobilePhone);
            customerPointsRecord.setStationId(enterpriseId);
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, -6);
            Date time = c.getTime();
            customerPointsRecord.setCreateTime(time);
            List<CustomerPointsRecord> customerPointsRecordList = customerPointsRecordService.getCustomerPointsRecordList(customerPointsRecord);
            resultData=ResultData.success(customerPointsRecordList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站油品积分规则信息 根据油企ID和油品名称
    @RequestMapping(value = "/getIntegralRuleListByOilNameAndStationId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取油站油品积分规则信息 根据油站ID和油品名称", httpMethod = "GET", notes = "获取油站油品积分规则信息 根据油站ID和油品名称")
    public String getIntegralRuleListByOilNameAndStationId(@ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId, String oilName, String oilType){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null && StringUtils.isNotBlank(oilName) && StringUtils.isNotBlank(oilType)){
            IntegralRule integralRule = new IntegralRule();
            integralRule.setStationId(enterpriseId);
            integralRule.setOilName(oilName);
            integralRule.setOilType(oilType);
            integralRule.setEmptyDate(new Date()); //有效期时间是否大于当前时间
            List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
            resultData=ResultData.success(integralRuleList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取油站积分规则信息 根据油站ID
    @RequestMapping(value = "/getIntegralRuleList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取油站积分规则信息", httpMethod = "GET", notes = "获取油站积分规则信息")
    public String getIntegralRuleList(@ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null){
            IntegralRule integralRule = new IntegralRule();
            integralRule.setStationId(enterpriseId);
            integralRule.setEmptyDate(new Date()); //有效期时间是否大于当前时间
            List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
            resultData=ResultData.success(integralRuleList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    @RequestMapping(value = "/getUserIntegralDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户积分明细", httpMethod = "GET")
    @ResponseBody
    public String getUserIntegralDetail(@ApiParam(value = "客户手机号", required = true)@RequestParam String mobilePhone,
                                        @ApiParam(value = "油站ID", required = true)@RequestParam Integer enterpriseId){

        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(mobilePhone) && enterpriseId !=null){
            CustomerPointsRecord customerPointsRecord  =new CustomerPointsRecord();
            customerPointsRecord.setMobilePhone(mobilePhone);
            customerPointsRecord.setStationId(enterpriseId);
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, -6);
            Date time = c.getTime();
            customerPointsRecord.setCreateTime(time);
            List<CustomerPointsRecord> customerPointsRecordList = customerPointsRecordService.getUserIntegralDetailList(customerPointsRecord);
            resultData=ResultData.success(customerPointsRecordList);
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    @RequestMapping(value = "/getMerchandiseOrderWrittenOff", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户积分商品订单是否核销", httpMethod = "GET")
    @ResponseBody
    public String getMerchandiseOrderWrittenOff(@ApiParam(value = "客户手机号", required = true)@RequestParam String mobilePhone,
                                                @ApiParam(value = "积分订单号", required = true)@RequestParam String integralOrderNo){
        logger.info("获取用户积分商品订单是否核销：客户手机号:{},积分订单号:{}",mobilePhone,integralOrderNo);
        return   pointsMerchandiseWriteOffRecordService.getIntegralOrderByOrderId(mobilePhone,integralOrderNo);
    }


}
